Google Docs 透過 Apps Script 能夠自動化處理各種文檔操作,
像是自動化編輯段落、插入圖片、設置格式等等,能夠大大提升文檔的處理效率!
那我們就來進入 Google doc App Script 的世界吧~
DocumentApp.create建立一個新的 Google Docs 文檔。
// Create a document
var doc = DocumentApp.create('My New Document');
Logger.log('新文檔已創建,文件ID: ' + doc.getId());
DocumentApp.openById// Open a document by ID.
var doc = DocumentApp.openById('DOCUMENT_ID');
// Get the document to which this script is bound.
var doc = DocumentApp.getActiveDocument();
var doc = DocumentApp.openByUrl('https://docs.google.com/document/d/{doc_id}/edit');
Body在 Google Docs 中,Body 是整個文檔的主要內容部分!它包含文檔中的所有段落、圖片、表格等元素。
你可以通過 DocumentApp.getActiveDocument().getBody() 來取得文檔的 Body,並且使用多種方法來操作和修改其內容。
Body 的主要結構是按以下層級組織的:
getParagraphsvar body = DocumentApp.getActiveDocument().getBody();
// 獲取所有段落
var paragraphs = body.getParagraphs();
for (var i = 0; i < paragraphs.length; i++) {
Logger.log(paragraphs[i].getText());
}
appendParagraph將文字插入到文檔中。
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
body.appendParagraph('我是被插入的段落文字');
editAsText設置文字的樣式,如粗體、斜體、字體大小等。
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paragraph = body.appendParagraph('我需要格式化!');
// 設置粗體和字體大小
paragraph.editAsText().setBold(true).setFontSize(14);
appendImage在文檔中插入圖片。
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var imageUrl = 'https://www.example.com/image.jpg'; // 替換為實際圖片URL
var imageBlob = UrlFetchApp.fetch(imageUrl).getBlob();
body.appendImage(imageBlob);
appendTable()插入一個表格並填充數據。
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var table = body.appendTable();
// 插入表頭
table.appendTableRow().appendTableCell('Name').appendTableCell('Age');
// 插入數據
table.appendTableRow().appendTableCell('John').appendTableCell('25');
table.appendTableRow().appendTableCell('Jane').appendTableCell('30');
以下整理了一些 Body 常用的方法:
| 方法 | 說明 | 
|---|---|
| appendParagraph(text) | 在 Body末尾添加一個段落。 | 
| insertParagraph(index, text) | 在指定索引處插入一個段落。 | 
| getParagraphs() | 獲取文檔中的所有段落。 | 
| appendTable() | 在 Body末尾添加一個空表格。 | 
| appendTable(table) | 在 Body末尾插入一個已有的表格。 | 
| getTables() | 獲取文檔中的所有表格。 | 
| appendImage(image) | 在 Body末尾插入一個圖片。 | 
| getImages() | 獲取文檔中的所有圖片。 | 
| getText() | 獲取 Body中的所有文本。 | 
| replaceText(searchPattern, replace) | 替換文檔中的某些文字。 | 
| getChild(index) | 獲取 Body中指定索引的元素。 | 
| getNumChildren() | 獲取 Body中子元素的數量。 | 
| getParent() | 獲取 Body的父元素,一般為Document。 | 
| clear() | 清空 Body的所有內容。 | 
| appendHorizontalRule() | 添加水平分隔線。 | 
| appendPageBreak() | 在 Body末尾插入分頁符號。 | 
| getFootnotes() | 獲取文檔中的所有註腳。 | 
詳細可以再看 google doc App Script 官方文件唷!
學完基本的文檔操作跟 Body 介紹後,
明天就來教大家認識  文字樣式(TextStyle) 和 段落樣式(ParagraphStyle) !